package com.manner.groupon.interceptor;

import cn.hutool.core.util.ObjUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import static com.manner.groupon.constant.CommonConstant.USER_LOGIN_PREV;

@Component
@Slf4j
public class UserInterceptor implements HandlerInterceptor {

    @Resource
    private RedisTemplate<String, JSONObject> redisTemplate;


    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //获取前端令牌
        String token = request.getHeader("X-Access-Token");
        //日志输出
        log.info("前端 token : {}", token);
        //判断
        if (StrUtil.isNullOrUndefined(token)) {
            response.setStatus(401);
            return false;
        }
        //查询缓存
        JSONObject jsonObject = redisTemplate.opsForValue().get(USER_LOGIN_PREV + token);

        System.out.println(jsonObject);
        //判断
        if (ObjUtil.isNull(jsonObject)) {
            response.setStatus(401);
            return false;
        }
        return true;
    }
}
